package com.linkdood.app.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linkdood.app.domain.MessageTemplate;
import com.linkdood.app.domain.NoticeMessage;
import com.linkdood.app.enums.MessageStatusEnum;
import com.linkdood.app.mapper.MessageTemplateMapper;
import com.linkdood.app.service.MessageTemplateService;
import com.linkdood.app.service.NoticeMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author huangshuo
 */
@Slf4j
@Service
public class MessageTemplateServiceImpl extends ServiceImpl<MessageTemplateMapper, MessageTemplate> implements MessageTemplateService {

    private final NoticeMessageService noticeMessageService;

    public MessageTemplateServiceImpl(NoticeMessageService noticeMessageService) {
        this.noticeMessageService = noticeMessageService;
    }


    @Override
    public void scanDoodTemplateMessage() {
        log.debug("start scan interactive template message, thread name is :{} ", Thread.currentThread().getName());
        this.dealDoingMessage();
    }

    @Override
    public void dealMessageResult(String bid, String token, String eventData) {
        Map<String, Object> map = new HashMap<>(1);
        map.put("bid", bid);
        List<MessageTemplate> templateMessages = baseMapper.selectByMap(map);
        if (templateMessages == null || templateMessages.isEmpty()) {
            return;
        }
        MessageTemplate templateMessage = templateMessages.get(0);
        templateMessage.setMToken(token);
        templateMessage.setResult(eventData);
        templateMessage.setUpdateTime(LocalDateTime.now());
        templateMessage.setStatus(MessageStatusEnum.DOING);
        save(templateMessage);
    }

    @Override
    public void dealDoingMessage() {
        Map<String, Object> map = new HashMap<>(1);
        map.put("status", MessageStatusEnum.DOING);
        List<MessageTemplate> templateMessages = baseMapper.selectByMap(map);
        if (templateMessages == null || templateMessages.isEmpty()) {
            return;
        }
        for (MessageTemplate template : templateMessages) {
            JSONObject eventData = new JSONObject();
            try {
                // TODO: 调用具体的处理消息结果的方法，抛出异常即处理失败，其他情况则处理成功

                eventData.put("cnName", "操作成功");
                eventData.put("enName", "success");
            } catch (Exception e) {
                log.error("dealDoingMessage failed, {}", e.getMessage());
                eventData.put("cnName", "操作失败");
                eventData.put("enName", "failed");
            } finally {
                if (!eventData.isEmpty()) {
                    NoticeMessage message = new NoticeMessage();
                    message.setThirdPartyId(template.getThirdPartyId());
                    message.setTitle("操作结果");
                    message.setContent(eventData.get("cnName").toString());
                    message.setType(3);
                    message.setStatus(0);
                    message.setStartTime(LocalDateTime.now());
                    message.setReserve1(eventData.toJSONString());
                    message.setReserve2(template.getBid());
                    message.setReserve3(template.getMToken());
                    message.setFromUser(template.getFromUserId());
                    message.setToUsers(template.getUserId());

                    noticeMessageService.save(message);

                    template.setUpdateTime(LocalDateTime.now());
                    template.setStatus(MessageStatusEnum.DONE);
                    save(template);
                }
            }
        }
    }
}

